'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { trpc } from '@/lib/trpc-provider'
import { copyToClipboard } from '@/lib/utils'
import { Copy, Play, RotateCcw, CheckCircle, XCircle, Info } from 'lucide-react'

interface RegexMatch {
  match: string
  index: number
  groups: string[]
}

export default function RegexTesterPage() {
  const [pattern, setPattern] = useState('')
  const [flags, setFlags] = useState('g')
  const [testString, setTestString] = useState('')
  const [result, setResult] = useState<{
    isMatch: boolean
    matches: string[]
    allMatches: RegexMatch[]
  } | null>(null)
  const [error, setError] = useState('')
  const [copySuccess, setCopySuccess] = useState<string | null>(null)

  const testMutation = trpc.tools.testRegex.useMutation({
    onSuccess: (data) => {
      if (data.success) {
        setResult({
          isMatch: data.isMatch,
          matches: data.matches,
          allMatches: data.allMatches
        })
        setError('')
      } else {
        setError(data.error || 'Unknown error')
        setResult(null)
      }
    },
    onError: (error) => {
      setError(error.message)
      setResult(null)
    }
  })

  const handleTest = () => {
    if (!pattern) {
      setError('请输入正则表达式')
      return
    }
    testMutation.mutate({ pattern, flags, testString })
  }

  const handleCopy = async (text: string, type: string) => {
    const success = await copyToClipboard(text)
    if (success) {
      setCopySuccess(type)
      setTimeout(() => setCopySuccess(null), 2000)
    }
  }

  const handleClear = () => {
    setPattern('')
    setFlags('g')
    setTestString('')
    setResult(null)
    setError('')
  }

  const commonPatterns = [
    {
      name: '邮箱地址',
      pattern: '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}',
      description: '匹配标准邮箱格式'
    },
    {
      name: '手机号码',
      pattern: '1[3-9]\\d{9}',
      description: '匹配中国大陆手机号'
    },
    {
      name: 'URL链接',
      pattern: 'https?:\\/\\/[^\\s]+',
      description: '匹配HTTP/HTTPS链接'
    },
    {
      name: 'IP地址',
      pattern: '\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b',
      description: '匹配IPv4地址'
    },
    {
      name: '日期格式',
      pattern: '\\d{4}-\\d{2}-\\d{2}',
      description: '匹配YYYY-MM-DD格式日期'
    },
    {
      name: '中文字符',
      pattern: '[\\u4e00-\\u9fa5]+',
      description: '匹配中文字符'
    }
  ]

  const flagOptions = [
    { value: 'g', label: 'g - 全局匹配', description: '查找所有匹配项' },
    { value: 'i', label: 'i - 忽略大小写', description: '不区分大小写' },
    { value: 'm', label: 'm - 多行模式', description: '^和$匹配每行的开始和结束' },
    { value: 's', label: 's - 单行模式', description: '.匹配包括换行符在内的所有字符' },
    { value: 'u', label: 'u - Unicode模式', description: '启用Unicode支持' },
    { value: 'y', label: 'y - 粘性匹配', description: '从lastIndex位置开始匹配' }
  ]

  const highlightMatches = (text: string, matches: RegexMatch[]) => {
    if (!matches.length) return text
    
    let result = text
    let offset = 0
    
    matches.forEach((match, index) => {
      const start = match.index + offset
      const end = start + match.match.length
      const highlighted = `<mark class="bg-yellow-200 px-1 rounded">${match.match}</mark>`
      result = result.slice(0, start) + highlighted + result.slice(end)
      offset += highlighted.length - match.match.length
    })
    
    return result
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            正则表达式测试器
          </h1>
          <p className="text-gray-600">
            测试和验证正则表达式，支持实时匹配和语法高亮
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Input Section */}
          <div className="lg:col-span-2 space-y-6">
            {/* Pattern Input */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">
                正则表达式
              </label>
              <div className="flex gap-2">
                <div className="flex-1 relative">
                  <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500">/</span>
                  <input
                    type="text"
                    value={pattern}
                    onChange={(e) => setPattern(e.target.value)}
                    placeholder="输入正则表达式"
                    className="w-full pl-8 pr-12 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono"
                  />
                  <span className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500">/{flags}</span>
                </div>
              </div>
            </div>

            {/* Flags */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">
                修饰符
              </label>
              <div className="flex flex-wrap gap-2">
                {flagOptions.map((flag) => {
                  const isSelected = flags.includes(flag.value)
                  return (
                    <button
                      key={flag.value}
                      onClick={() => {
                        if (isSelected) {
                          setFlags(flags.replace(flag.value, ''))
                        } else {
                          setFlags(flags + flag.value)
                        }
                      }}
                      className={`px-3 py-1 text-xs rounded border ${
                        isSelected
                          ? 'bg-blue-100 border-blue-300 text-blue-700'
                          : 'bg-gray-50 border-gray-300 text-gray-600 hover:bg-gray-100'
                      }`}
                      title={flag.description}
                    >
                      {flag.label}
                    </button>
                  )
                })}
              </div>
            </div>

            {/* Test String */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">
                测试文本
              </label>
              <textarea
                value={testString}
                onChange={(e) => setTestString(e.target.value)}
                placeholder="输入要测试的文本"
                className="w-full h-32 p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            {/* Controls */}
            <div className="flex gap-4">
              <Button onClick={handleTest} disabled={testMutation.isLoading}>
                <Play className="w-4 h-4 mr-2" />
                {testMutation.isLoading ? '测试中...' : '测试'}
              </Button>
              <Button variant="outline" onClick={handleClear}>
                <RotateCcw className="w-4 h-4 mr-2" />
                清空
              </Button>
            </div>

            {/* Results */}
            {error && (
              <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
                <div className="flex items-center gap-2 text-red-700">
                  <XCircle className="w-5 h-5" />
                  <span className="font-medium">错误</span>
                </div>
                <p className="text-red-600 mt-1">{error}</p>
              </div>
            )}

            {result && (
              <div className="space-y-4">
                {/* Match Status */}
                <div className={`p-4 rounded-lg border ${
                  result.isMatch 
                    ? 'bg-green-50 border-green-200' 
                    : 'bg-gray-50 border-gray-200'
                }`}>
                  <div className="flex items-center gap-2">
                    {result.isMatch ? (
                      <CheckCircle className="w-5 h-5 text-green-600" />
                    ) : (
                      <XCircle className="w-5 h-5 text-gray-500" />
                    )}
                    <span className={`font-medium ${
                      result.isMatch ? 'text-green-700' : 'text-gray-700'
                    }`}>
                      {result.isMatch ? '匹配成功' : '无匹配'}
                    </span>
                  </div>
                  {result.allMatches.length > 0 && (
                    <p className="text-sm text-gray-600 mt-1">
                      找到 {result.allMatches.length} 个匹配项
                    </p>
                  )}
                </div>

                {/* Highlighted Text */}
                {result.allMatches.length > 0 && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <label className="text-sm font-medium text-gray-700">
                        高亮显示
                      </label>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleCopy(testString, 'highlighted')}
                      >
                        <Copy className="w-4 h-4 mr-2" />
                        {copySuccess === 'highlighted' ? '已复制' : '复制'}
                      </Button>
                    </div>
                    <div 
                      className="p-3 bg-gray-50 border rounded-lg font-mono text-sm whitespace-pre-wrap"
                      dangerouslySetInnerHTML={{
                        __html: highlightMatches(testString, result.allMatches)
                      }}
                    />
                  </div>
                )}

                {/* Match Details */}
                {result.allMatches.length > 0 && (
                  <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-700">
                      匹配详情
                    </label>
                    <div className="space-y-2 max-h-64 overflow-y-auto">
                      {result.allMatches.map((match, index) => (
                        <div key={index} className="p-3 bg-blue-50 border border-blue-200 rounded">
                          <div className="flex items-center justify-between mb-2">
                            <span className="text-sm font-medium text-blue-900">
                              匹配 #{index + 1}
                            </span>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleCopy(match.match, `match-${index}`)}
                            >
                              <Copy className="w-3 h-3 mr-1" />
                              {copySuccess === `match-${index}` ? '已复制' : '复制'}
                            </Button>
                          </div>
                          <div className="space-y-1 text-sm">
                            <div>
                              <span className="text-blue-700 font-medium">内容:</span>
                              <code className="ml-2 px-2 py-1 bg-white rounded">{match.match}</code>
                            </div>
                            <div>
                              <span className="text-blue-700 font-medium">位置:</span>
                              <span className="ml-2">{match.index}</span>
                            </div>
                            {match.groups.length > 0 && (
                              <div>
                                <span className="text-blue-700 font-medium">分组:</span>
                                <div className="ml-2 space-y-1">
                                  {match.groups.map((group, groupIndex) => (
                                    <div key={groupIndex}>
                                      <code className="px-2 py-1 bg-white rounded text-xs">
                                        ${groupIndex + 1}: {group}
                                      </code>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Common Patterns */}
          <div className="space-y-4">
            <h2 className="text-lg font-semibold text-gray-900">
              常用正则表达式
            </h2>
            
            <div className="space-y-3">
              {commonPatterns.map((item, index) => (
                <div key={index} className="p-3 border border-gray-200 rounded-lg hover:bg-gray-50">
                  <div className="flex items-center justify-between mb-2">
                    <h3 className="font-medium text-gray-900">{item.name}</h3>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setPattern(item.pattern)}
                    >
                      使用
                    </Button>
                  </div>
                  <code className="text-xs bg-gray-100 px-2 py-1 rounded block mb-2">
                    {item.pattern}
                  </code>
                  <p className="text-xs text-gray-600">{item.description}</p>
                </div>
              ))}
            </div>

            {/* Help */}
            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <div className="flex items-center gap-2 mb-2">
                <Info className="w-4 h-4 text-blue-600" />
                <h3 className="font-medium text-blue-900">使用提示</h3>
              </div>
              <ul className="text-xs text-blue-700 space-y-1">
                <li>• 使用转义字符 \\ 来匹配特殊字符</li>
                <li>• () 用于创建捕获组</li>
                <li>• [] 用于字符类匹配</li>
                <li>• + 匹配一个或多个</li>
                <li>• * 匹配零个或多个</li>
                <li>• ? 匹配零个或一个</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}